<template>
  <!-- 实时告警 -->
  <div class="tableContent">
    <a-button
      v-if="subDatas.length"
      type="primary"
      style="margin: 4px 0 12px 0"
      @click="batchConfirm"
      >批量确认</a-button
    >
    <a-table
      :dataSource="tableData"
      :columns="columns"
      size="small"
      :scroll="{ x: 'max-content' }"
      @resizeColumn="handleResizeColumn"
      :pagination="false"
      :loading="tableLoading"
      :row-selection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange,
      }"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'evtType'">
          {{
            EVT_TYPE.filter((item) => item.value === record.evtType)[0]?.label
          }}
        </template>
        <template v-if="column.key === 'evtStatus'">
          {{ record.evtStatus === 0 ? "未确认" : "已确认" }}
        </template>
        <template v-if="column.key === 'warnLevel'">
          <div :class="record.warnLevel === 3 ? 'redCircle' : ''">
            {{ warnLevelList[record.warnLevel] }}
          </div>
        </template>
        <template v-if="column.key === 'pdValue'">
          <a-tooltip placement="topLeft">
            <template #title>{{ record.pdValue }}</template>
            {{ record.pdValue }}
          </a-tooltip>
        </template>
        <template v-if="column.key === 'handle'">
          <a-button
            v-hasPermission="'errorComfirm'"
            type="link"
            @click="handleComfirm(record)"
            >确认告警</a-button
          >
        </template>
      </template>
    </a-table>
    <a-pagination
      v-model:current="filterForm.current"
      v-model:page-size="filterForm.size"
      :total="total"
      position="bottomRight"
      show-size-changer
      @change="getWarnRecordPage"
      :show-total="(total) => `总共 ${total} 条`"
    >
      <template #buildOptionText="props">
        <span>{{ props.value }}条/页</span>
      </template>
    </a-pagination>
  </div>

  <Comfirm
    :comfirmVisible="comfirmVisible"
    :rowData="rowData"
    @update:comfirmVisible="(val) => (comfirmVisible = val)"
    @getWarnRecordPage="getWarnRecordPage"
  />
</template>
<script setup>
import Comfirm from "./comfirm.vue"
import { formatMillisecondsToDHM } from "@/utils/common"
import { EVT_TYPE } from "@/constants/stationConfig.js"
const $api = inject("$api")
const props = defineProps({
  stationInfo: {
    type: Object,
  },
})
const filterForm = ref({
  size: 10,
  current: 1,
})
const total = ref(0)
const tableData = ref([])
const tableLoading = ref(false)
const comfirmVisible = ref(false)
const commonColumnProps = {
  width: 180,
  resizable: true,
  align: "center",
}

const isChargeProject = computed(
  () => props.stationInfo?.isChargeProject || false
)

const columns = computed(() => {
  if (isChargeProject.value) {
    // 储充电站 特有的列
    const specificColumns = [
      {
        title: "电站",
        dataIndex: "stationName",
        key: "stationName",
        ...commonColumnProps,
        width: 200,
      },
      {
        title: "电池堆",
        dataIndex: "linkName",
        key: "linkName",
        ...commonColumnProps,
        width: 200,
      },
      {
        title: "电池簇",
        dataIndex: "blockName",
        key: "blockName",
        ...commonColumnProps,
        width: 150,
      },
      {
        title: "告警类别",
        dataIndex: "evtType",
        key: "evtType",
        ...commonColumnProps,
        width: 120,
      },
      {
        title: "告警信息",
        dataIndex: "noRuleWarnMessage",
        key: "noRuleWarnMessage",
        ...commonColumnProps,
        width: 200,
      },
      {
        title: "告警状态",
        dataIndex: "evtStatus",
        key: "evtStatus",
        ...commonColumnProps,
        width: 150,
      },
      {
        title: "告警开始时间",
        dataIndex: "startTime",
        key: "startTime",
        ...commonColumnProps,
      },
      /* {
        title: "告警结束时间",
        dataIndex: "endTime",
        key: "endTime",
        ...commonColumnProps,
      },
      {
        title: "告警持续时间",
        dataIndex: "updateTime",
        key: "updateTime",
        ...commonColumnProps,
      }, */
      {
        title: "告警确认时间",
        dataIndex: "confirmTime",
        key: "confirmTime",
        ...commonColumnProps,
      },
      {
        title: "确认内容",
        dataIndex: "confirmMessage",
        key: "confirmMessage",
        ...commonColumnProps,
      },
      {
        title: "操作",
        dataIndex: "handle",
        key: "handle",
        ...commonColumnProps,
      },
    ]
    return [...specificColumns]
  }

  // 非储充电站的列
  const stationSpecificColumns = [
    {
      title: "告警等级",
      dataIndex: "warnLevel",
      key: "warnLevel",
      ...commonColumnProps,
      width: 200,
    },
    {
      title: "pack",
      dataIndex: "packNumber",
      key: "packNumber",
      ...commonColumnProps,
      width: 120,
    },
    {
      title: "电芯",
      dataIndex: "batteryNumber",
      key: "batteryNumber",
      ...commonColumnProps,
    },
    {
      title: "告警触发",
      dataIndex: "maintenanceAdvice",
      key: "maintenanceAdvice",
      ...commonColumnProps,
      width: 120,
    },
    {
      title: "告警规则",
      dataIndex: "ruleName",
      key: "ruleName",
      ...commonColumnProps,
    },
    {
      title: "实时pdData值",
      dataIndex: "pdValue",
      key: "pdValue",
      ...commonColumnProps,
      width: 160,
      ellipsis: true,
      customCell: (record) => ({
        style: {
          whiteSpace: "nowrap",
          overflow: "hidden",
          textOverflow: "ellipsis",
          maxWidth: "160px",
        },
      }),
    },
    {
      title: "告警信息",
      dataIndex: "warnMessage",
      key: "warnMessage",
      ...commonColumnProps,
      width: 200,
    },
    {
      title: "告警状态",
      dataIndex: "evtStatus",
      key: "evtStatus",
      ...commonColumnProps,
      width: 150,
    },
    {
      title: "电池堆",
      dataIndex: "linkName",
      key: "linkName",
      ...commonColumnProps,
      width: 200,
    },
    {
      title: "电池簇",
      dataIndex: "blockName",
      key: "blockName",
      ...commonColumnProps,
      width: 150,
    },
    {
      title: "告警开始时间",
      dataIndex: "startTime",
      key: "startTime",
      ...commonColumnProps,
    },
    /*  {
      title: "告警结束时间",
      dataIndex: "endTime",
      key: "endTime",
      ...commonColumnProps,
    },
    {
      title: "告警持续时间",
      dataIndex: "updateTime",
      key: "updateTime",
      ...commonColumnProps,
    }, */
    {
      title: "告警确认时间",
      dataIndex: "confirmTime",
      key: "confirmTime",
      ...commonColumnProps,
    },
    {
      title: "确认内容",
      dataIndex: "confirmMessage",
      key: "confirmMessage",
      ...commonColumnProps,
    },
    {
      title: "操作",
      dataIndex: "handle",
      key: "handle",
      ...commonColumnProps,
    },
  ]
  return [...stationSpecificColumns]
})
const warnLevelList = {
  1: "新巨能一级（预警）",
  2: "新巨能二级（报警）",
  3: "新巨能三级（报警）",
}
const getWarnRecordPage = async () => {
  const params = {
    ...filterForm.value,
    stationId: props.stationInfo.id,
    evtStatus: 0,
  }

  // 非储充电站传 evtStatus 参数
  /* if (!isChargeProject.value) {
    params.evtStatus = 0; // 只显示未确认的数据
  } */

  tableLoading.value = true

  // 根据电站类型选择不同的 API
  const res = isChargeProject.value
    ? await $api.chargeEvtList(params)
    : await $api.warnRecord(params)

  tableLoading.value = false
  if (res && res.code === 0) {
    tableData.value = res.data.records.map((item, index) => ({
      ...item,
      key: item.id,
      index: index + 1,
      offTime: item.hasOwnProperty("warnDuration")
        ? formatMillisecondsToDHM(item.warnDuration)
        : "--",
    }))
    total.value = res.data.total
  }
}
const rowData = ref({})
const handleComfirm = async (record) => {
  rowData.value = record
  comfirmVisible.value = true
}
const selectedRowKeys = ref([])
const subDatas = ref([])
const onSelectChange = (selectedKeys, selectedRows) => {
  selectedRowKeys.value = selectedKeys
  subDatas.value = selectedRows.map((row) => row.id)
}
//批量确认
const batchConfirm = async () => {
  const res = await $api.warnConfirmBatch(subDatas.value)
  if (res && res.code === 0) {
    message.success("确认成功")
    subDatas.value = []
    getWarnRecordPage()
  }
}
const handleChageStation = () => {
  getWarnRecordPage()
}
onMounted(() => {})
defineExpose({ handleChageStation })
</script>
<style lang="less" scoped>
.tableContent {
  border-radius: 4px;
  background-color: #141414;
  padding: 8px;
}
.ant-table {
  .ant-btn {
    padding: 4px 5px;
  }
}
.redCircle {
  color: red;
}
.custom-tooltip {
  background-color: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 8px;
  border-radius: 4px;
  z-index: 1000;
}
</style>
